package com.screw.carnival.sdk.utils;

import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;

public class SCarnivalUtils {

    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding"; // 或 AES/ECB/PKCS5Padding
    private static final String ALGORITHM = "AES";
    private static final String CHARSET = "UTF-8";

    // 固定密钥（示例值，需替换）
    private static final String FIXED_KEY = "ewwe23DTtS23dw23";

    // 固定IV（16字节，示例值，需替换）
    private static final String FIXED_IV = "23wewreds534DS23"; // 长度必须16字节

    /**
     * 加密（相同明文输出相同密文）
     */
    public static String encrypt(String plainText) throws Exception {
        byte[] keyBytes = generateKey(FIXED_KEY);
        SecretKeySpec secretKey = new SecretKeySpec(keyBytes, ALGORITHM);

        // 使用固定IV
        IvParameterSpec ivSpec = new IvParameterSpec(FIXED_IV.getBytes(CHARSET));

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(CHARSET));

        return Base64.encodeToString(encryptedBytes, Base64.NO_WRAP);
    }

    /**
     * 解密
     */
    public static String decrypt(String encryptedText) {
        try {
            byte[] encryptedBytes = Base64.decode(encryptedText, Base64.NO_WRAP);

            byte[] keyBytes = generateKey(FIXED_KEY);
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, ALGORITHM);
            IvParameterSpec ivSpec = new IvParameterSpec(FIXED_IV.getBytes(CHARSET));

            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

            return new String(decryptedBytes, CHARSET);
        }catch (Exception e){
            e.printStackTrace();
        }
       return "";
    }

    /**
     * 生成固定密钥
     */
    private static byte[] generateKey(String key) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(key.getBytes(CHARSET));
        // AES-256：取32字节 | AES-128：取前16字节
        byte[] truncated = new byte[32];
        System.arraycopy(hash, 0, truncated, 0, truncated.length);
        return truncated;
    }
}
